package com.anbao.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import android.os.Environment;
/**
 * 读取和写入系统的配置文件
 * @author tiansl
 *
 */
public class FileUtil {


	/**
	 * 读取配置文件
	 */
	public static void readSystemConfig(){
		String filePath  = getSDPath()+"/anbao/config/system"; 
		
		
		File file = new File(filePath);
		if(!file.exists()){
			return;
		}
		
		FileReader reader = null;
		try {
			reader = new FileReader(file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		BufferedReader breader = new BufferedReader(reader);
		String lineStr = "";
		
		try {
			while((lineStr = breader.readLine())!=null){
				if(lineStr!=null&&lineStr.length()>0){
					
					fillData(lineStr);
				}
			
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 解析填充数据
	 * @param lineStr
	 */
	private static void fillData(String lineStr) {
		String[] result =	lineStr.split("=");
		
		if("usrid".equals(result[0])){
			SystemUtil.usrId = Long.parseLong(result[1]);
		}else if("pwd".equals(result[0])){
			
			SystemUtil.pwd = result[1];
			
		}
		
	}


	/**
	 * 写配置文件
	 */
	public static void writeSystemConfig(){
		String filePath  = getSDPath()+"/anbao/config"; 
		
		File file = new File(filePath);
		if(!file.exists()){
			
			file.mkdirs();
		}
		
		try {
			FileWriter w = new FileWriter(new File(filePath+"/system"));
			w.write(getWriteData());
			w.flush();
			w.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 将内存中的数据序列化，然后写到文件中去
	 * @return
	 */
	private static String getWriteData() {
		
		StringBuffer sb = new StringBuffer();
		sb.append("usrid").append("=").append(SystemUtil.usrId);
		sb.append("\n").append("pwd").append("=").append(SystemUtil.pwd);
		return sb.toString();
	}


	/**
	 * 获取SD卡的路径
	 * @return
	 */
	public static String getSDPath(){
	       File sdDir = null;
	       boolean sdCardExist = Environment.getExternalStorageState()  
	                           .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
	       if   (sdCardExist)  
	       {                              
	         sdDir = Environment.getExternalStorageDirectory();//获取跟目录
	      }  
	       return sdDir.toString();
	      
	} 
}
